package com.example.managemyself.api.repository;

import com.example.managemyself.api.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户数据访问层
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    /**
     * 根据用户名查找用户
     */
    Optional<User> findByUsername(String username);
    
    /**
     * 根据邮箱查找用户
     */
    Optional<User> findByEmail(String email);
    
    /**
     * 根据用户名或邮箱查找用户
     */
    @Query("SELECT u FROM User u WHERE u.username = :usernameOrEmail OR u.email = :usernameOrEmail")
    Optional<User> findByUsernameOrEmail(@Param("usernameOrEmail") String usernameOrEmail);
    
    /**
     * 检查用户名是否存在
     */
    boolean existsByUsername(String username);
    
    /**
     * 检查邮箱是否存在
     */
    boolean existsByEmail(String email);
    
    /**
     * 根据角色查找用户
     */
    List<User> findByRole(User.Role role);
    
    /**
     * 根据状态查找用户
     */
    List<User> findByStatus(User.Status status);
    
    /**
     * 根据角色和状态查找用户
     */
    List<User> findByRoleAndStatus(User.Role role, User.Status status);
    
    /**
     * 分页查询活跃用户
     */
    Page<User> findByStatus(User.Status status, Pageable pageable);
    
    /**
     * 模糊搜索用户（用户名、全名、邮箱）
     */
    @Query("SELECT u FROM User u WHERE " +
           "u.username LIKE %:keyword% OR " +
           "u.fullName LIKE %:keyword% OR " +
           "u.email LIKE %:keyword%")
    Page<User> searchUsers(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 查找最近登录的用户
     */
    @Query("SELECT u FROM User u WHERE u.lastLoginTime >= :since ORDER BY u.lastLoginTime DESC")
    List<User> findRecentlyActiveUsers(@Param("since") LocalDateTime since);
    
    /**
     * 统计用户数量按角色
     */
    @Query("SELECT u.role, COUNT(u) FROM User u GROUP BY u.role")
    List<Object[]> countUsersByRole();
    
    /**
     * 统计用户数量按状态
     */
    @Query("SELECT u.status, COUNT(u) FROM User u GROUP BY u.status")
    List<Object[]> countUsersByStatus();
    
    /**
     * 更新用户最后登录时间
     */
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.lastLoginTime = :loginTime WHERE u.id = :userId")
    void updateLastLoginTime(@Param("userId") Long userId, @Param("loginTime") LocalDateTime loginTime);
    
    /**
     * 批量更新用户状态
     */
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.status = :status WHERE u.id IN :userIds")
    void updateUserStatus(@Param("userIds") List<Long> userIds, @Param("status") User.Status status);
    
    /**
     * 删除长时间未活跃的用户
     */
    @Modifying
    @Transactional
    @Query("DELETE FROM User u WHERE u.lastLoginTime < :cutoffDate AND u.status = :status")
    void deleteInactiveUsers(@Param("cutoffDate") LocalDateTime cutoffDate, @Param("status") User.Status status);
    
    /**
     * 查找创建时间在指定范围内的用户
     */
    @Query("SELECT u FROM User u WHERE u.createdAt BETWEEN :startDate AND :endDate ORDER BY u.createdAt DESC")
    List<User> findUsersCreatedBetween(@Param("startDate") LocalDateTime startDate, 
                                       @Param("endDate") LocalDateTime endDate);
    
    /**
     * 统计新用户注册数量（按日期）
     */
    @Query("SELECT DATE(u.createdAt) as date, COUNT(u) as count FROM User u " +
           "WHERE u.createdAt >= :startDate GROUP BY DATE(u.createdAt) ORDER BY DATE(u.createdAt)")
    List<Object[]> getNewUserRegistrationStats(@Param("startDate") LocalDateTime startDate);
} 